<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="类型" class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in centerTypeOptions" :key="key" :label="value" :value="key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >

      <el-table-column label="ID" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template slot-scope="{row}">
          <span>{{ centerTypeOptions[row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center">
        <template slot-scope="{row}">
          <span><a :href="returnImageUrl(row.url)" target="_blank" rel="noopener">{{ returnImageUrl(row.url) }}</a></span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" align="center" sortable="custom" :class-name="getSortClass('sort')">
        <template slot-scope="{row}">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <!-- <el-button type="success" size="mini" @click="handleUpdateRoleMenu(row,$index)">
            菜单
          </el-button> -->
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" class="filter-item">
            <el-option v-for="(value,key) in centerTypeOptions" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" clearable />
        </el-form-item>
        <el-form-item label="地址" prop="url">
          <el-input v-model="temp.url" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="temp.sort" clearable />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormroleMenuListVisible">
      <el-form ref="dataMenuForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item>
          <el-tree
            ref="tree"
            :data="roleMenuList"
            :default-checked-keys="roleMenuDefaultList"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormroleMenuListVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateRoleMenu()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import { roleList, roleCreate, roleUpdate, roleDelete, menuList, roleMenuList, roleMenuUpdate } from '@/api/rbac'
// import { menuList, roleMenuList, roleMenuUpdate } from '@/api/rbac'
import { centerConfigPage, centerConfigCreate, centerConfigUpdate, centerConfigDelete } from '@/api/system'
import waves from '@/directive/waves' // waves directive
import { formatJson, notifySuccess, my_confirm, getFileUrl } from '@/utils/tool'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'RoleMenuList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        type: undefined,
        name: undefined,
        url: undefined,
        sort: undefined
      },
      temp: {
        id: undefined,
        // parent_id: '',
        name: '',
        type: '',
        url: '',
        sort: ''
      },
      centerTypeOptions: [],
      dialogFormVisible: false,
      dialogFormroleMenuListVisible: false,
      roleMenuList: [], // 所有的菜单
      roleMenuDefaultList: [], // 默认选中的菜单
      roleMenuListId: '',
      defaultProps: {
        children: 'menuTwo',
        label: 'name'
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        menu: '菜单'
      },
      rules: {
        type: [{ required: true, message: '类型必填', trigger: 'change' }],
        name: [{ required: true, message: '名称必填', trigger: 'change' }],
        url: [{ required: true, message: '地址必填', trigger: 'change' }],
        sort: [{ required: true, message: '排序必填', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      centerConfigPage(this.listQuery).then(response => {
        this.list = response.data.list
        this.centerTypeOptions = response.data.typeList
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        name: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          centerConfigCreate(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          centerConfigUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        centerConfigDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '名称']
        const filterVal = ['id', 'name']
        const data = formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户角色表'
        })
        this.downloadLoading = false
      })
    },
    returnImageUrl(url) {
      return getFileUrl(url)
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
